import {loginApi,logoutApi} from "@/services/user.service";
import {setToken,removeToken} from "@/utils/token";
import $router from '@/router/index'
import {ILoginForm} from "@/types/login";


export default {
    namespaced: true,
    state:{
        token:'',
        user_id:0
    },
    getters: {
        getToken(state:any){
            return state.token
        }
    },
    mutations: {
        SET_TOKEN(state:any, token:string) {
            state.token = token
        },
        SET_USERID(state:any, user_id:number) {
            state.user_id = user_id
        },
        REMOVE_TOKEN(state:any){
            state.token=''
        },
        REMOVE_USERID(state:any){
            state.user_id=0
        },


    },
    actions: {
        /**
         * 发送登录请求
         * @param {any} commit
         * @param {any} state
         * @param {any} loginForm
         * @returns {Promise<void>}
         */
        async asyncLogin({commit}, loginForm: ILoginForm) {
            let {data} = await loginApi(loginForm);
            if (data) {
                //保存token到sessionStorage
                setToken(data['session_token'])

                //保存token到store
                commit('SET_TOKEN', data['session_token'])
                commit('SET_USERID', data['user_id'])
                // await dispatch('asyncUserInfo')
                await $router.push('/home')

            }
        }
        ,
        /**
         * 退出登录
         * @param commit
         * @param {any} dispatch
         * @param token
         * @returns {Promise<void>}
         */
        async asyncLogout({commit}) {
            //有token才发送请求
            console.log('userStore.ts-asyncLogout-token')
                await logoutApi();
                //清空数据
                // dispatch('resetStore')
                //从sessionStorage中清除token
                commit('REMOVE_TOKEN')
                commit('REMOVE_USERID')
                removeToken()
                //跳转到首页
                await $router.push('/login')



        }
        ,

    }

}
